import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ki5k_video/utils/Utils.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';

import '../widget/bottom_bar_widget.dart';
import '../models/tabIcon_data.dart';
import '../resources/AppTheme.dart';
import 'download/index.dart';
import 'home/index_page.dart';
import 'discover/index_page.dart';
import 'personal/index_page.dart';
import '../api/Api.dart';


class MainScreen extends StatefulWidget {
  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> with TickerProviderStateMixin {
  AnimationController animationController;

  List<TabIconData> tabIconsList = TabIconData.tabIconsList;

  Widget tabBody = Container(
    color: AppTheme.background,
  );

  int exitMis;

  @override
  void initState() {
    super.initState();

    if(!mounted) return;
    loadUpdate();

    tabIconsList.forEach((TabIconData tab) {
      tab.isSelected = false;
    });

    tabIconsList[0].isSelected = true;

    animationController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this );
    tabBody = HomePage();
  }

  // 检测版本更新， 利用码云进行更新
  Future<void> loadUpdate() async {
    final versionData = await Api.getAppVersion();
    if( versionData != null && versionData['code'] == 0 ){
        final buildInfo = await PackageInfo.fromPlatform();
        if(int.parse(buildInfo.buildNumber) < versionData['versionCode']){
          print('版本更新');
          
          final select = await UtilTool.showAlertDialog(context, versionData['modifyContent'] ?? '', title: '更新提示', lefText: '', righText: '前往浏览器更新');
          if(select != null && select){
            String url = Platform.isAndroid ? versionData['androidUrl'] : versionData['iosUrl'];
            if (await canLaunch(url)) {
              await launch(url, forceSafariVC: false);
            } else {
              throw "打开appStore$url";
            }
          }
        }
    }
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // bool isFullScreen = Provider.of<ApplicationStatus>(context, listen: true).isFullscreen;
    return WillPopScope(
      onWillPop: () {
        // 退出APP方法二
        // UtilTool.showAlertDialog(
        //   context,
        //   '您确定要退出达理吗?',
        //   title: '温馨提示',
        //   lefText: '放弃',
        //   righText: '确定'
        // ).then((data) async {
        //   // 判断是否点击确定按钮
        //   if(data != null && data){
        //     debugPrint('点击确认按钮');
        //     exit(0);
        //   }
        // });
        // 退出APP方法一
        int now = DateTime.now().millisecondsSinceEpoch;
        if( exitMis !=null && (exitMis+20000)>now){
          exit(0);
        } else {
          exitMis = now;
          UtilTool.showToastDialog('请再次点击退出', type: false);
        }
        return Future.value(false);
      }, // look here!
      child:Container(
        color: AppTheme.background,
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: FutureBuilder<bool>(
            future: getData(),
            builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
              if (!snapshot.hasData) {
                return const SizedBox();
              } else {
                return tabBody;
              }
            },
          ),
          bottomNavigationBar: bottomBar(),
        ),
      ),
    );
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 200));
    return true;
  }

  Widget bottomBar() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        BottomBarView(
          tabIconsList: tabIconsList,
          addClick: () {},
          changeIndex: (int index) {
            if (!mounted) {
              return;
            }
            setState(() {
              switch (index) {
                case 1:
                  tabBody = DiscoverPage();
                  break;
                case 2:
                  // tabBody = DownloadPage();
                  tabBody = PersonalPage();
                  break;
                case 3:
                  tabBody = PersonalPage();
                  break;
                default:
                  tabBody = HomePage();
                  break;
              }
            });
          },
        ),
      ],
    );
  }
}
